#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# (c) Copyright 2010 - BidiX@BidiX.info
#
#
'''
    api_handler - provide ApiHandler class
    
    Description :
 
     Usage :
     
'''

from google.appengine.ext import webapp
from bidix.db import *
from bidix.html import ustr


class ApiHandler(webapp.RequestHandler):
    '''
    classdocs
    '''
    kind_classes = {
                    'article': Article,
                    }

    def initialize(self, request, response):
        webapp.RequestHandler.initialize(self, request, response)
        self.kind = self.match.groupdict()['kind']
        if self.kind_classes.has_key(self.kind):
            self.kind_class = self.kind_classes[self.kind]
        else:
            self.kind_class = None
        self.name = self.match.groupdict()['name']
        self.format = self.match.groupdict()['format']
        self.url = self.request.url
        self.response.headers['Content-Type'] = 'text/plain; charset=utf-8' 
        if (self.format=='.html') or (self.format=='.form'):
                self.response.headers['Content-Type'] = 'text/html; charset=utf-8' 
        if self.format=='.xml':
                self.response.headers['Content-Type'] = 'text/xml; charset=utf-8' 
            
        self.with_html_editor=True
                

    def get(self, *args):
        """Handler method for GET requests."""
        if self.kind_class == None:
            self.error(404)
            return
        if not self.name:
            self.get_list(*args)
        else:
            entity = self.kind_class.get_by_name(self.name)
            if entity:
                if self.format == ".html":
                    result = entity.format_to_html()
                elif self.format == ".xml":
                    result = entity.format_to_xml()
                elif self.format == ".form":
                    result = entity.format_to_form(self.url)
                else:
                    result = entity.format_to_txt()
            else:
                if self.format == '.form':
                    entity = self.kind_class(self.name,name=self.name)
                    result = entity.format_to_form(self.url)
                else:
                    self.error(404)
                    return
            self.writeln(result)
       
            
    def get_list(self,  *args):
        entities = self.kind_class.all()
        ids = []
        for entity in entities:
            self.writeln(entity.key().id_or_name())
        
    def put(self, *args):
        """Handler method for POST requests."""
        params = self.request.params
        key_name = None
        kwds = {}
        for (name, value) in params.items():
            #value = ustr(value)
            name = ustr(name)
            if name == 'name':
                key_name = value
            if name == 'tags':
                value_list = value.strip().split(' ')
                value = value_list
            kwds[name]=value
        self.kind_class.add_or_replace(key_name,**kwds)
        self.writeln(key_name)

    def head(self, *args):
        """Handler method for HEAD requests."""
        self.error(405)

    def options(self, *args):
        """Handler method for OPTIONS requests."""
        self.error(405)

    def post(self, *args):
        """Handler method for PUT requests."""
        self.put(*args)

    def delete(self, *args):
        """Handler method for DELETE requests."""
        self.error(405)

    def trace(self, *args):
        """Handler method for TRACE requests."""
        self.error(405)

    def error(self, code):
        """Clears the response output stream and sets the given HTTP error code.

        Args:
          code: the HTTP status error code (e.g., 501)
        """
        self.response.set_status(code)
        self.response.clear()
        self.writeln(str(code) + " - " + webapp.Response.http_status_message(code))
   


    def write(self, str):
        self.response.out.write(str)
 
    def writeln(self, str):
        self.write(str)
        self.response.out.write('\n')
    
